import { getStoredFileHandle, openDB, storeFileHandle } from '@/lib/indexedDb';

let db: IDBDatabase | null = null;
async function getDB() {
  if (db) {
    return db;
  } else {
    db = await openDB();
    return db;
  }
}

let directoryHandle: FileSystemDirectoryHandle | null = null;

export function useDirectoryHandle() {
  const key = 'collect-giga-product-directory-handle';
  const [gigaCatetoryDirectoryHandle, setgigaCatetoryDirectoryHandle] =
    useState<FileSystemDirectoryHandle | null>(null);

  const getDirectoryHandle = useCallback(async () => {
    if (directoryHandle) {
      return directoryHandle;
    }
    const db = await getDB();
    if (db) {
      const handle = await getStoredFileHandle(db, key);
      if (handle) {
        // 检查当前权限状态
        const permission = await handle.queryPermission({ mode: 'readwrite' });
        if (permission === 'granted') {
          // 权限有效，使用句柄
          directoryHandle = handle;
          return handle;
        } else {
          try {
            // 请求新权限
            const newPermission = await handle.requestPermission({ mode: 'readwrite' });
            if (newPermission === 'granted') {
              // 权限已授予
              directoryHandle = handle;
              return handle;
            } else {
              console.log('用户拒绝了权限');
            }
          } catch (error) {
            // 如果没有用户交互,那么这个时候请求新权限会报错
          }
        }
      }
    }
    const newDirectoryHandle = await window.showDirectoryPicker({
      mode: 'readwrite',
    });
    await storeFileHandle(newDirectoryHandle, key, db);
    directoryHandle = newDirectoryHandle;
    return newDirectoryHandle;
  }, [key]);

  // 获取括号目录
  useEffect(() => {
    getDirectoryHandle().then((directoryHandle) => {
      setgigaCatetoryDirectoryHandle(directoryHandle);
    });
  }, [getDirectoryHandle]);

  async function setCollectDirectoryHandle() {
    const newDirectoryHandle = await window.showDirectoryPicker({
      mode: 'readwrite',
    });
    if (db) {
      await storeFileHandle(newDirectoryHandle, key, db);
    } else {
      db = await getDB();
      await storeFileHandle(newDirectoryHandle, key, db);
    }
    directoryHandle = newDirectoryHandle;
    setgigaCatetoryDirectoryHandle(directoryHandle);
  }
  return {
    getDirectoryHandle,
    setCollectDirectoryHandle: useCallback(setCollectDirectoryHandle, [key]),
    gigaCatetoryDirectoryHandle,
  };
}
